#
# Copyright 2010 Steve Leach
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
#

import logging
import base64

from google.appengine.ext import webapp
from google.appengine.ext import db
from eveoperation import Pilot, PilotRole

def add_rest_mappings(mappings):
	mappings.append(('/rest/test', RestDemoHandler))
	mappings.append(('/rest/pilots', PilotListHandler))
	mappings.append(('/rest/oproles', PilotRoleHandler))

class RestCredentials(db.Model):
	id =  db.StringProperty(required=True)
	password = db.StringProperty(required=True)

class RestHandler(webapp.RequestHandler):

	def get(self):
		if RestCredentials.all().count() == 0:
			creds = RestCredentials(id='A', password='B')
			creds.put()

		is_auth = False
		if self.request.headers.has_key('Authorization'):
			auth = self.request.headers['Authorization'];
			creds = base64.b64decode(auth[6:])
			uid, pw = creds.split(':')
		
			creds = RestCredentials.gql('WHERE id = :1 AND password = :2', uid, pw).get()
			
			if creds:
				is_auth = True

		self.response.headers["Content-Type"] = "text/plain"

		if is_auth:
			self.do_get()
		else:
			self.error(401)
			self.response.out.write('Not authorised')

	def do_get(self):
		pass

	def writeVal(self, value):
		self.response.out.write(value)
		self.response.out.write('\t')

	def writeDate(self, value):
		self.response.out.write(value)
		self.response.out.write('\t')

	def newLine(self):
		self.response.out.write('\n')

class RestDemoHandler(RestHandler):

	def do_get(self):
		logging.info('RestDemoHandler invoked')
		self.write('Hello world\n')

class PilotListHandler(RestHandler):
	
	def do_get(self):
		logging.info('AltList invoked')

		pilots = Pilot.all()
		pilots.order('char_name')

		self.response.out.write('name\tmain\t')		
		self.response.out.write('\n')
		for pilot in pilots:
			if pilot.char_name:
				self.response.out.write(str(pilot.char_name)+'\t')
				if pilot.main_char:
					self.response.out.write(str(pilot.main_char))
				self.response.out.write('\t')
				self.response.out.write('\n')

class PilotRoleHandler(RestHandler):

	def do_get(self):
		logging.info('PilotRole list invoked')

		data = PilotRole.all()

		self.response.out.write('op\tdate\tpilot\trole\n')		
		for value in data:
			self.writeVal(str(value.op_id))
			self.writeDate(value.op_date)
			self.writeVal(value.pilot_name)
			self.writeVal(value.role)				
			self.newLine()

